import { ReceiptPrintService } from './salesreceipt/salesreceipt.component';
import { TestPrintService } from './testprint/testPrint.component';
import { Order } from './../../../../model/clerkDataContext';
import { Component } from '@angular/core';

export class PrintComponentService {
    static current = new PrintComponentService();
    private printerContainerComponent: PrinterContainerComponent;
    regist(component: PrinterContainerComponent) {
        this.printerContainerComponent = component;
    }

    show(printParams: PrintParams) {
        if (!printParams.isTestPrint) {
            let data = {
                store: printParams.store,
                token: printParams.token,
                preOrder: printParams.preOrder,
                printers: printParams.printers
            }
            ReceiptPrintService.current.bindData(data);
        } else {
            let data = {
                store: printParams.store,
                token: printParams.token,
                auxPrintTestDevice: printParams.printers[0]
            }
            TestPrintService.current.bindData(data);
        }
        return new Promise((resolve, reject) => {
            this.printerContainerComponent.onResult = (data) => {
                if(!printParams.isTestPrint){
                    ReceiptPrintService.current.clearData();
                } else {
                    TestPrintService.current.clearData();
                }
                resolve(data);
            }
        });
    }
}

@Component({
    selector: "print-container",
    template: `
        <sales-receipt (createPrintTask)="createPrintTask($event)"></sales-receipt>
        <test-print (createPrintTask)="createPrintTask($event)"></test-print>
    `
})
export class PrinterContainerComponent {
    constructor() {
        PrintComponentService.current.regist(this);
    }

    createPrintTask(data) {
        this.onResult(data);
    }
    onResult;
}

export interface PrintParams {
    token: string;
    preOrder?: Order;
    store;
    isTestPrint: boolean;
    printers;
}